package com.asa.mvvm_aop_frame.basic.ext

import android.content.Context
import android.os.Build
import android.os.Environment
import java.io.File

/**
 * create By：anderson
 * on 2022/4/27
 * desc:
 */


//---------------------------------------------------文件系统start----------------------------------------------------
const val TYPE_IMAGE = 1
const val TYPE_VIDEO = 2
const val TYPE_AUDIO = 3
const val TYPE_DOWNLOAD = 4
const val TYPE_DOCUMENT = 5
fun Context.createDir(type:Int,subFolder:String?):File?{

    var sub =subFolder
    if (sub != null&&sub.startsWith("/")&& sub.length>1){
        sub = sub.substring(1,sub.length)
    } else{
        sub = ""
    }

    var rootDir : File? = null
    rootDir = if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.Q){
        getRootDirFile(type)
    } else{
        val state: String = Environment.getExternalStorageState()
        if (state == Environment.MEDIA_MOUNTED) Environment.getExternalStorageDirectory() else cacheDir
    }
    return rootDir?.also {
        if (!it.exists()){
            it.mkdirs()
        }
    }?.let {
        File(
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
                it.getAbsolutePath().toString() + "/" + sub
            else
                it.getAbsolutePath().toString() + getParentPath(type, sub)
        )
    }?.also {
        if (!it.exists()) {
            it.mkdirs()
        }
    }
}

fun Context.getRootDirFile(type: Int): File? {
    return when (type) {
        TYPE_VIDEO -> getExternalFilesDir(Environment.DIRECTORY_MOVIES)
        TYPE_AUDIO -> getExternalFilesDir(Environment.DIRECTORY_MUSIC)
        TYPE_IMAGE -> getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        TYPE_DOWNLOAD -> getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        TYPE_DOCUMENT -> getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
        else -> getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    }
}


fun Context.getParentPath(
    type: Int,
    subFolder: String?
): String {
    var sub = subFolder
    if (sub != null && sub.startsWith("/") && sub.length > 1) {
        sub = sub.substring(1, sub.length)
    } else {
        sub = ""
    }
    return when (type) {
        TYPE_VIDEO -> "/" + packageName + "/video/" + sub
        TYPE_AUDIO -> "/" + packageName + "/audio/" + sub
        TYPE_IMAGE -> "/" + packageName + "/image/" + sub
        TYPE_DOWNLOAD -> "/" + packageName + "/download/" + sub
        TYPE_DOCUMENT -> "/" + packageName + "/document/" + sub
        else -> "/" + packageName + "/download/" + sub
    }
}